﻿using System;
using System.Collections.Generic;
using System.IO;

namespace Zinnia.Extensions
{
    /// <summary>
    /// 流扩展
    /// </summary>
    public static class StreamExtend
    {
        /// <summary>
        /// 将流读取成字节组。
        /// </summary>
        /// <param name="stream">流。</param>
        /// <returns>字节组。</returns>
        public static byte[] ReadBytes(this Stream stream)
        {
            if (!stream.NotNull("stream").CanRead)
                throw new NotSupportedException(stream + "can not read!");
            Action trySeekBegin = () =>
            {
                if (!stream.CanSeek)
                    return;
                stream.Seek(0, SeekOrigin.Begin);
            };
            trySeekBegin();
            var list = new List<byte>(stream.CanSeek ? (stream.Length > int.MaxValue ? int.MaxValue : (int)stream.Length) : 300);
            int b;
            while ((b = stream.ReadByte()) != -1)
                list.Add((byte)b);
            trySeekBegin();
            return list.ToArray();
        }
    }
}
